<template>
  <div class="app-container">
    <el-form
      ref="userinfo"
      :rules="rules_userinfo"
      :model="temp_userinfo"
      label-position="left"
      label-width="70px"
      style="width: 400px; margin-left: 50px"
    >
      <el-form-item
        :label="$t('手机号')"
        prop="mobile"
      >
        <el-input v-model="temp_userinfo.mobile" />
      </el-form-item>
      <el-form-item
        :label="$t('密码')"
        prop="password"
      >
        <el-input
          v-model="temp_userinfo.password"
          type="password"
        />
      </el-form-item>
      <el-button
        type="primary"
        @click="submit"
      >保存</el-button>
    </el-form>
  </div>
</template>

<script>
import { createUser } from '@/ucenter/api/user'
export default {
  data() {
    const validateMobile = (rule, value, callback) => {
      var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/
      if (!myreg.test(value)) {
        this.$message({
          message: rule.message,
          type: 'error'
        })
        callback(new Error())
      } else {
        callback()
      }
    }
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.message,
          type: 'error'
        })
        callback(new Error())
      } else {
        callback()
      }
    }
    return {
      temp_userinfo: {
        mobile: '',
        password: ''
      },
      rules_userinfo: {
        mobile: [{ validator: validateMobile, message: '请输入有效手机号', trigger: 'blur' }],
        password: [{ validator: validateRequire, message: '密码为必填字段', trigger: 'blur' }]
      }
    }
  },
  methods: {
    submit() {
      this.$refs.userinfo.validate(valid => {
        if (valid) {
          const data = this.temp_userinfo
          createUser(data).then(res => {
            if (res.data.status === '0') {
              this.$notify({
                title: '成功',
                message: '添加用户成功',
                type: 'success',
                duration: 2000
              })
              this.$router.push('/ucenter/user/index')
            } else {
              this.$message({
                message: '添加失败',
                type: 'error'
              })
            }
          })
        } else {
          console.log('2')
        }
      })
    }
  }
}
</script>

<style>
</style>
